/**
 * All Widget depend on jQuery
 *
 */
(function() {
	var HZBank = this.HZBank || (this.HZBank = {});
	HZBank.Widget = HZBank.Widget || (this.HZBank.Widget = function() {
	});
	var Utils = HZBank.Utils;
	var $ = this.$ || this.jQuery;
	var _ = this._;
	var logger = HZBank.Core.logger;
	// static function for hzbank widget
	baseStaticFunction = {
		extend : function(name, base, protoProps, staticProps) {
			var child;
			if (!$.isFunction(base)) {
				protoProps = base;
				base = HZBank.Widget;
			}

			var ns = name.split(".");

			for ( var i = 0; i < ns.length - 1; i++) {
				if (base[ns[i]] === undefined) {
					base.extend(ns[i], base);
				}
				base = base[ns[i]];
			}

			// HZBank.Core.extend(base ? base : HZBank.Widget.Base, protoProps);
			if (protoProps && protoProps.hasOwnProperty('constructor')) {
				child = protoProps.constructor;
			} else {
				child = function() {
					base.apply(this, arguments);
				};
			}
			var bsf = $.extend(this.deepCopy(base.baseStaticFunction), (staticProps || {}));
			// static method
			// TODO performance issue???
			$.extend(child, bsf, {
				// used for extend static method
				baseStaticFunction : bsf
			});

			// prototype medhot
			// var tpFn = function() {
			// };
			// tpFn.prototype = base.prototype;
			// var tpObj = new tpFn();
			$.extend(child.prototype, this.deepCopy(base.prototype), protoProps || {});

			child.prototype.constructor = child;

			base[ns[ns.length - 1]] = child;
			return child;
		},
		// copy JSON object
		deepCopy : function(obj) {
			var tpObj = {};
			for ( var i in obj) {
				tpObj[i] = $.isPlainObject(obj[i]) ? this.deepCopy(obj[i]) : obj[i];
			}
			return tpObj;
		}
	};

	// add static function
	$.extend(HZBank.Widget, baseStaticFunction, {
		baseStaticFunction : baseStaticFunction
	});


	// Start of Checkbox
	var Checkbox = function(element, options) {
		this.$element = $(element);
		this.options = $.extend({}, $.fn.checkbox.defaults, options);
		$('<i class="checkbox"></i>').insertAfter(this.$element);
		this.$label = this.$element.parent();
		this.$label.addClass('ui-checkbox-label');
		this.$check = this.$label.find('input[type=checkbox]');
		this.groupName = this.$check.attr('name');
		this.$icon = this.$label.find('i');
		this.$chk = this.$label.find('input[type=checkbox]');
		this.setState(this.$chk);
		this.$chk.on('change', $.proxy(this.itemchecked, this));
	};

	Checkbox.prototype = {
		constructor : Checkbox,
		setState : function($chk) {
			var checked = $chk.is(':checked');
			var disabled = $chk.is(':disabled');

			this.$icon.removeClass('checked').removeClass('disabled');

			if (checked === true) {
				this.$icon.addClass('checked');
			}
			if (disabled === true) {
				this.$icon.addClass('disabled');
			}
		},
		/*
		 * 设置控件新值
		 * @param val
		 * 			1. String 对应值
		 * 			2. Array 对应列表值
		 * 			3.
		 */
		value : function(val) {
			if ($.isArray(val)) {
				this.$check.get(0).checked = ($.inArray(this.$check.val(), val) !== -1 || ($.isNumeric(this.$check.val()) && $.inArray(
						Number(this.$check.val()), val) !== -1));
			} else {
				this.$check.get(0).checked = (this.$check.val() === val);
			}
			this.refresh();
		},
		/*
		 * 根据实际值刷新控件
		 *
		 * */
		refresh : function() {
			if (this.$chk.is(':checked')) {
				this.$icon.addClass('checked');
			}else{
				this.$icon.removeClass('checked');
			}
		},
		reset : function() {
			this.$chk.removeAttr("checked");
			this.refresh();
		},
		/*
		 * 启用控件
		 *
		 * */
		enable : function() {
			this.$chk.attr('disabled', false);
			this.$icon.removeClass('disabled');
		},
		/*
		 * 禁用控件
		 *
		 * */
		disable : function() {
			this.$chk.attr('disabled', true);
			this.$icon.addClass('disabled');
		},
		toggle : function() {
			this.$chk.click();
		},
		/*
		 * 点击控件后刷新控件
		 *
		 * */
		itemchecked : function(e) {
			var chk = $(e.target);
			this.setState(chk);
		}
	};

	$.fn.checkbox = function(option, value) {
		var methodReturn = null;
		var $set = this.filter('[type="checkbox"]').each(function() {
			var $this = $(this);
			var data = $this.data('checkbox');
			var options = typeof option === 'object' && option;
			if (!data) {
				$this.data('checkbox', (data = new Checkbox(this, options)));
			}
			if (typeof option === 'string') {
				methodReturn = data[option](value);
			}
		});
		return (methodReturn === null) ? $set : methodReturn;
	};
	$.fn.checkbox.defaults = {};
	$.fn.checkbox.Constructor = Checkbox;
	$.fn.checkmust = function(tar){
	       var target;
		    if(tar){
				target = $(tar).filter('[type="checkbox"]').length>0 ? $(tar).filter('[type="checkbox"]').eq(0) : "null";
			}else{
				target = $(this).filter('[type="checkbox"]').length>0 ? $(this).filter('[type="checkbox"]').eq(0) : "null";
			}
			if(target!="null"){
				var that = this;
				var selfID = $(this).attr("id")
				target.parent("label").parent().find("input[type=checkbox]").change(function(){
					var eventID =$(this).attr("id");
					var f = $(this).parent().parent().children();
					var length = f.length;
					var index=f.index($(this).parent());
					if(eventID==selfID){
						if($(this).is(':checked')){
							f.find("i").removeClass('checked');
			//				f.find("input[type=checkbox]:lt(1)").attr('checked',false)
							$(this).attr("checked",'checked');
							$(this).next("i").addClass('checked')
							for(var i=0;i<length;i++){
								if(i!=index){
									f.eq(i).find("input").attr("checked",false)
								}
							}
			//				alert(f.last().find("i").attr("class"))
						}
					}else{
						$(that).next("i").removeClass('checked');
						$(that).attr('checked',false);
					}
				})
			}
		
	}
	// End of Checkbox

	// Start of Radio
	var Radio = function(element, options) {
		this.$element = $(element);
		this.options = $.extend({}, $.fn.radio.defaults, options);
		$('<i class="radio"></i>').insertAfter(this.$element);
		this.$label = this.$element.parent();
		this.$label.addClass('ui-radio-label');
		this.$icon = this.$label.find('i');
		this.$radio = this.$label.find('input[type=radio]');
		this.groupName = this.$radio.attr('name');
		this.setState(this.$radio);
		this.$radio.on('change', $.proxy(this.itemchecked, this));
	};
	Radio.prototype = {
		constructor : Radio,
		setState : function($radio) {
			var checked = $radio.is(':checked');
			var disabled = $radio.is(':disabled');
			if (checked === true) {
				this.$icon.addClass('checked');
			}
			if (disabled === true) {
				this.$icon.addClass('disabled');
			}
		},
		value : function(val) {
			if (this.$radio.val() == val) {
				this.reset();
				this.$radio.get(0).checked = true;
				this.setState(this.$radio);
			}
		},
		/*
		 * 根据实际值刷新控件
		 *
		 */
		refresh : function() {
			if (this.$radio.is(':checked')) {
				this.$icon.addClass('checked');
			}else{
				this.$icon.removeClass('checked');
			}
		},
		/*
		 * 重置控件
		 *
		 */
		reset : function() {
			$('input[name="' + this.groupName + '"]').each(function(){
				$(this).get(0).checked = false;
				$(this).next().removeClass('checked');
			});
		},
		/*
		 * 重置控件样式
		 *
		 */
		resetClass : function() {
			$('input[name="' + this.groupName + '"]').next().removeClass('checked');
		},
		/*
		 * 启用控件
		 *
		 */
		enable : function() {
			this.$radio.attr('disabled', false);
			this.$icon.removeClass('disabled');
		},
		/*
		 * 禁用控件
		 *
		 */
		disable : function() {
			this.$radio.attr('disabled', true);
			this.$icon.addClass('disabled');
		},
		/*
		 * 点击控件后刷新控件
		 *
		 */
		itemchecked : function(e) {
			var radio = $(e.target);
			this.resetClass();
			this.setState(radio);
		}
	};
	$.fn.radio = function(option, value) {
		var methodReturn = null;
		var $set = this.each(function() {
			var $this = $(this);
			var data = $this.data('radio');
			var options = typeof option === 'object' && option;
			if (!data)
				$this.data('radio', (data = new Radio(this, options)));
			if (typeof option === 'string')
				methodReturn = data[option](value);
		});
		return (methodReturn === null) ? $set : methodReturn;
	};
	$.fn.radio.defaults = {};
	$.fn.radio.Constructor = Radio;
	// End of Radio

	// Start of Select
	var Select = function(element, options) {
		this.$select = $(element);
		this.$element = $('<div class="ui-hz-widget ui-select">');
		this.$element.insertAfter(this.$select).append(this.$select);
		this.$element.addClass(this.$select.attr('class'));
		this.options = $.extend({}, $.fn.select.defaults, options);
		this.$button = $('<div class="ui-select-button" tabIndex=0>');
		this.$text = $('<span>').addClass('ui-select-text');
		var $icon = $('<span>').addClass('ui-select-icon');
		this.$button.append(this.$text, $icon);

		this.$dropdown = $('<div class="ui-select-dropdown">');
		this.$ul = $('<ul>');
		this.$element.append(this.$button, this.$dropdown.append(this.$ul));

		this.init();

		// Remove this function and pull it to View, Widget only care about itself.
		if (this.options.url || this.options.remote) {
			this.loadData();
		} else {
			this.refresh();
		}

		this.addEvents();
		if(this.$select.attr('data-dropdirect')){
			this.$select.selectfix();
		}
	};
	Select.prototype = {
		constructor : Select,
		init : function() {
			//console.log(2222)
			this.options.type = this.$select.is('[multiple]') ? 'M' : 'S';
			this.options.dropup = this.options.dropup || this.$select.data('dropup');
			if (this.options.dropup) {
				this.$element.addClass('ui-select-dropup');
			}

			this.options.parent = this.options.parent || this.$select.data('parent');
			if (this.options.parent) {
				$(this.options.parent).append(this.$dropdown);
				this.$dropdown.addClass('ui-select-dropdown-out');
			}

			if (this.$select.is('[disabled]') || this.$select.is('[disabled="true"]') || this.$select.is('[readonly]')
					|| this.$select.is('[readonly="readonly"]')) {
				this.$element.addClass('ui-select-disabled');
			}

			// set width
//			this.$element.width(this.$select.outerWidth());
			var width = this.options.width || this.$select.data('width');
			var height = this.options.height || this.$select.data('height');
			var _width = this.options.dropwidth || this.$select.data('dropwidth');
			if (width) {
				this.options.width = width;
				this.$element.width(width);
			}
			if(height){
				this.options.height = height;
				this.$dropdown.css('max-height',height);
			}
			if(_width){
				this.options.dropwidth = _width;
				this.$dropdown.width(_width);
			}
			var value = this.$select.data('value');
			if (this._isMultiple()) {
				this.$element.addClass('ui-select-multiple');
				if (value !== undefined) {
					value = value + '';
					value = value.split(',');
					value = $.map(value, function(val) {
						return $.trim(val);
					});
				}
			}
			this.options.value = this.options.value || value;
			this.options.key = this.options.key || this.$select.data('key');
			this.options.table = this.options.table || this.$select.data('table');
		},
		// Remove this function and pull it to View
		loadData : function() {
			var key = this.options.key,
				table = this.options.table;
			// if key exist, load data from server;
			if (key && HZBank.Utils && HZBank.Utils.getSelects) {
				HZBank.Utils.getSelects({
					url : this.options.url,
					el : this.$select,
					type : key,
					success : $.proxy(this.refresh, this)
				});
				this.$select.removeData('key');
				return true;
			}
			return false;
		},
		enable : function() {
			var _this = this;
			this.$select.removeAttr('disabled');
			this.$element.removeClass('ui-select-disabled');
			this.$dropdown.off('click.ui-select', 'li').on('click.ui-select', 'li', function(e) {
				//e.stopPropagation() //阻止事件冒泡
				// e.preventDefault();
				// Shall I improve it?
				// if (_this._isMultiple() && $(e.target).is('label')) {
				// // return;
				// }
				var $this = $(this), obj = [];
				if (_this._isSingle()) {
					obj = $this.data('ui-select-data')
				} else if (_this._isMultiple()) {
					var $lis = _this.$ul.find('input:checked').parent().parent();
					$lis.each(function() {
						obj.push($(this).data('ui-select-data'));
					});
				}
				_this._chooseWithEvent(obj);
			});
			this.$dropdown.removeClass('disableClass')
		},
		disable : function() {
			this.$select.attr('disabled', true);
			this.$element.addClass('ui-select-disabled');
			this.disableOpen();
		},
		disableclick:function(){
			this.$element.addClass('ui-select-disabled');
			this.disableOpen();
		},
		reset : function() {
			this.$select.val(this.options.value);
			this.choose(this._getObj(this.options.value));
			this._refreshCheckbox();
		},
		/*
		 * 根据值来获取对象
		 *
		 * */
		_getObj : function(value) {
			var obj;
			if (this._isSingle()) {
				var $option = this.$select.find('option[value="' + value + '"]');
				if ($option.length === 0) {
					$option = this.$select.find('option:eq(0)');
					value = $option.val();
				}
				obj = {
					text : $.trim($option.text()),
					val : value
				};
			} else if (this._isMultiple()) {
				var opts = this.$element.find('option');
				value = _.sortBy(value, function(val) {
					return opts.index(opts.filter('[value="' + val + '"]'));
				});
				obj = [];
				for ( var i in value) {
					var $opt = this.$select.find('option[value="' + value[i] + '"]');
					if ($opt.length) {
						obj.push({
							text : $.trim($opt.text()),
							val : value[i]
						});
					}
				}
			}
			return obj;
		},
		/*
		 * 根据实际值刷新控件
		 *
		 * */
		refresh : function() {
			this.refreshList();
			var obj = this._getObj(this.options.value === undefined ? this.$select.val() : this.options.value);
			this.choose(obj);
			this._refreshCheckbox();
		},
		getindex:function(title){
			var that = this;
			var li =  that.$dropdown.find("li");
			var curr;
			var _title = title;
			
			for(var i=0;i<li.length;i++){
				curr = li.eq(i).attr('title');
				if(curr == _title){
					return i;
				}
			}
		},
		focus:function(){
			var that = this;
			var li_index;
			if(!this.$select.attr('disabled')){
				this.$button.unbind("keydown").bind("keydown",function(e){
					var index = e.keyCode;
					var title = that.$button.find("span.ui-select-text").attr('title');
						li_index =that.getindex(title);
					var length = that.$dropdown.find("li").length;
					var _title;
					if(index==39 || index==40){
						if(li_index+2>length){
							_title = that.$dropdown.find("li").eq(0).attr('title');
							li_index = 0;
						}else{
							_title = that.$dropdown.find("li").eq(li_index+1).attr('title');
							li_index++;
						}
					}else if(index==37 || index==38){
						if(li_index==0){
							_title = that.$dropdown.find("li").eq(length-1).attr('title');
							li_index = that.$dropdown.find("li").length-1;
						}else{
							_title = that.$dropdown.find("li").eq(li_index-1).attr('title');
							li_index--;
						}
					}
					that.$button.find("span.ui-select-text").attr('title',_title);
					that.$button.find("span.ui-select-text").html(_title);
					var val = that.$dropdown.find('ul li').eq(li_index).data('val');
					that.$select.val(val);
					
				})
				this.$button.unbind("blur").bind('blur',function(){
					that.$button.unbind("keydown")
				})
			}
		},
		addEvents : function() {
			var _this = this;
			this.$button.bind('focus.ui-select', $.proxy(this.focus, this));
			this.$button.bind('click.ui-select', $.proxy(this.open, this));
			this.$dropdown.on('click.ui-select', 'li', function(e) {
				//e.stopPropagation() //阻止事件冒泡
				// e.preventDefault();
				// Shall I improve it?
				// if (_this._isMultiple() && $(e.target).is('label')) {
				// // return;
				// }
				var $this = $(this), obj = [];
				if (_this._isSingle()) {
					obj = $this.data('ui-select-data')
				} else if (_this._isMultiple()) {
					var $lis = _this.$ul.find('input:checked').parent().parent();
					$lis.each(function() {
						obj.push($(this).data('ui-select-data'));
					});
				}
				_this._chooseWithEvent(obj);
				if(_this._isSingle()){
					$this.parent().children('li').removeClass('select-choose');
					$this.addClass('select-choose');
					$this.parent().children('li').eq(0).removeClass('select-choose');
				}
			});
		},
		_isSingle : function() {
			return this.options.type === $.fn.select.TYPE.SINGLE;
		},
		_isMultiple : function() {
			return this.options.type === $.fn.select.TYPE.MULTIPLE;
		},
		_refreshCheckbox : function(){
			if (this._isMultiple()) {
				var $checkbox = this.$element.find('input[type=checkbox]');
				$checkbox.removeAttr('checked');
				var vals = this.$select.val() || [];
				for ( var i = 0; i < vals.length; i++) {
					this.$element.find('li[data-val="' + vals[i] + '"]').find('input[type=checkbox]').prop('checked',true);
				}
				$checkbox.checkbox('refresh');
			}
		},
		/*
		 * 用户选择事件
		 *
		 */
		_chooseWithEvent : function(obj) {
			if (this.options.before) {
				var ret = this.options.before(obj);
				if (ret === false) {
					this.close();
					return;
				}
			}
			this.choose(obj);
			if (this._isSingle()) {
				this.close();
			}
			if (this.options.after) {
				this.options.after(obj);
			}
		},
		/*
		 * 选择对应项
		 *
		 * @param obj{JSON}
		 * 			val		: 内部值
		 * 			text	: 显示内容
		 *
		 */
		choose : function(obj) {
			if (this._isSingle()) {
				this.$text.text(obj.text).attr('title', obj.text);
				this.$select.val(obj.val);
			} else if (this._isMultiple()) {
				var arrs = [], text = '';
				for ( var i = 0; i < obj.length; i++) {
					text += ', ' + obj[i].text;
					arrs.push(obj[i].val);
				}
				text = text.substring(2, text.length);
				this.$select.val(arrs);
				this.$text.text(text).attr('title', text);
			}
		},
		/*
		 * 设置参数
		 *
		 * @param opts{JSON}
		 *
		 */
		option : function(opts) {
			this.options = $.extend(this.options, opts);
		},
		/*
		 * 根据刷新控件列表
		 *
		 * */
		refreshList : function() {
			this.$ul.empty();
			this.list = {};
			var $opts = this.$select.find('option');
			var values = this.$select.val();
			for ( var i = 0; i < $opts.length; i++) {
				var $opt = $opts.eq(i);
				var $li = $('<li>');
				var obj = {
					text : $opt.text(),
					val : $opt.val()
				};
				this.list[obj.val] = obj;
				$li.data('ui-select-data', obj).attr({
					'data-val' : obj.val,
					'title' : obj.text
				});
				if (this.options.type === $.fn.select.TYPE.MULTIPLE) {
					var $label = $('<label>');
					var $checkbox = $('<input type="checkbox">');
					if ($.inArray(obj.val, values) !== -1) {
						$checkbox.attr('checked', true);
					}
					if(obj.val === ""){
						//如果值为空，表示是请选择，则不增加多选框
						$label.append(obj.text);
						$li.append($label);
					}else{
						$label.append($checkbox).append(obj.text);
						$li.append($label);
						$checkbox.checkbox();
					}
				} else {
					$li.text(obj.text);
				}
				this.$ul.append($li);
			}
		},
		/*
		 * 边界判断
		 *
		 */
		judBorder:function(){
			var that = this,
				left = this.$dropdown.offset().left,
				width = this.$dropdown.width();
			if(width + left > $("body").width()){
				var po_left = this.$element.width() - width;
				this.$dropdown.css('left',po_left);
			}
			
		},
		disableOpen:function(){
			if(!this.$dropdown.hasClass('disableClass')){
				this.$dropdown.addClass('disableClass');
			}
			this.$dropdown.off('click');
		},
		/*
		 * 打开下拉菜单
		 *
		 */
		open : function(event) {
			//event.stopPropagation() //阻止事件冒泡
			event.preventDefault();
			if (this.$element.is('.ui-select-open')) {
				this.close();
				return;
			}
			if(this.$element.is('.ui-select-disabled')){
				this.disableOpen();
			}
			if (this.options.parent) {
				this._setOutDropListPosition();
				this.$dropdown.show();
				$(window).bind('resize.ui-select', $.proxy(this._setOutDropListPosition, this));
			}
			this.$element.toggleClass('ui-select-open');
			$(document).bind('mousedown.ui-select', $.proxy(this.close, this));
//			this.$dropdown.mCustomScrollbar("destroy");
//			this.$dropdown.mCustomScrollbar({
//					  theme:"dark"
//			  })
			  this.judBorder();
		},
		/*
		 * 如果不在控件内部的下拉菜单，显示时需要更新下拉菜单位置
		 *
		 */
		_setOutDropListPosition : function(e) {
			var offset = this.$element.offset();
			this.$dropdown.css({
				width : this.$element.width(),
				top : offset.top + this.$element.height(),
				left : offset.left
			});
		},
		/*
		 * 关闭下拉菜单
		 *
		 */
		close : function(event) {
			if (event && this.$element.add(this.$dropdown).find(event.target).size() != 0) {
				return;
			}
			if (this.options.parent) {
				this.$dropdown.hide();
			}
			$(document).unbind('mousedown.ui-select');
			$(window).unbind('resize.ui-select');
			this.$element.removeClass('ui-select-open');
		},
		/*
		 * 设置控件新值
		 *
		 */
		value : function(val) {
			if (val === undefined) {
				return this.$select.val();
			}
			if (this.$element) {
				this.choose(this._getObj(val));
				this._refreshCheckbox();
			} else {
				this.$select.data('value', val);
			}
		},
		/*
		 * 获取/设置title值
		 *
		 */
		title : function(title) {
			if (title === '') {
				this.$element.removeAttr('title');
			}else{
				this.$element.attr('title', title);
			}
		},
		error : function(err) {
			if (err) {
				this.$element.addClass('error');
			} else {
				this.$element.removeClass('error');
			}
		},
		/*
		 * 设置新下拉列表
		 *
		 */
		data : function(arrs) {
			this.$select.empty();
			this.$select.append($('<option value=""></option>').text('请选择'));
			for ( var i = 0; i < arrs.length; i++) {
				var item = arrs[i];
				this.$select.append($('<option>').attr('value', item.val).text(item.text));
			}
			this.refresh();
		}

	};

	$.fn.select = function(option, value) {
		var methodReturn = null;
		var $set = this.each(function() {
			var $this = $(this);
			var data = $this.data('select');
			var options = typeof option === 'object' && option;
			if (!data) {
				$this.data('select', (data = new Select(this, options)));
			}
			if (typeof option === 'string') {
				methodReturn = data[option](value);
			}
		});
		return (methodReturn === null) ? $set : methodReturn;
	};

	$.fn.select.defaults = {
		type : 'S'
	};
	$.fn.select.TYPE = {
		MULTIPLE : 'M',
		SINGLE : 'S'
	};
	$.fn.select.Constructor = Select;
	$.fn.selectload = function(callback){
		var $el = $(this);
		var types = $.makeArray($el.map(function(i, el) {
			var $this = $(el);
			if ($this.parent().is('.ui-select')) {
				return;
			}
			////console.log($this.data('parentId'));
			return {
				key : $this.data('key'),
				table : $this.data('table') || 'para',
				parentId : $this.data('parentId') || $this.data('parentid')||'false'
			};
		}));
		HZBank.Utils.getSelects({
			els : $el,
			types : types,
			success : function() {
				$el.select();
				if(typeof callback =='function'){
					callback();	
				}
			}
		});
	};
	$.fn.selectfix = function(tar){
		var $target;
		if(tar){
			$target = tar; 
		}else{
			$target = $("body");
		}
		var top,height;
		var $el = $(this);
//		$el.each(function(i){
//			$(this).attr('selectfix-top',top).attr('selectfixed-height',height);		
//			
//		})
		var that = this;
		 $(this).next(".ui-select-button").unbind('click.dropmode').bind('click.dropmode',function(){
				 if($(this).next().css("display")=="block"){
					var s_top = $target.offset().top;
					var s_height = $target.height();
					var d =  $(this).prev().attr('data-dropdirect'); 
					if(d){	
						if(d=='top'){
							selectfix({top:s_top,height:s_height},$(this),'top')
						}else{
							return;
						}
					}else{
						selectfix({top:s_top,height:s_height},$(this))
					}
				 }
				 
		})
	};
	
	//cardNum 再次初始化 start
	$.fn.cardNumReset = function(callback){
		$('input[data-type="cardNum"]').each(function(){
			var myVal = HZBank.Utils.Rules.cardNum($(this).val());
			$(this).val(myVal);
			if($(this).val().length >= 23){
				var setVal = $(this).val().substring(0, 23);
				$(this).val(setVal);
			}
		});
		$('input[data-type="cardNum"]').css({'font-weight':'bold'}).unbind('input propertychange').bind('input propertychange',function(){
			var myVal = HZBank.Utils.Rules.cardNum($(this).val());
			$(this).val(myVal);
			if($(this).val().length >= 23){
				var setVal = $(this).val().substring(0, 23);
				$(this).val(setVal);
			}
		});
	};
	//cardNum 再次初始化 end
	
	function selectfix(con,el){
		    var config = con;
			var $el = el;
			var display = $el.next('.ui-select-dropdown');
			var top = parseInt(config.top);
			var height = parseInt(config.height);
			var selftop = $el.offset().top+$el.height();
			var selfheight = display.height();
//			console.log('selfheight:----------'+selfheight+'-----selftop:'+selftop+'------'+top+'---------'+height);
//				 display.mCustomScrollbar("destroy");
//				  display.mCustomScrollbar({
//						  theme:"dark"
//				  })
			
			if((selfheight+5+selftop>top+height) || arguments.length==3){
					 display.css("top",(selfheight*(-1))-1);
					 display.css("box-shadow","0px -2px 10px rgba(0, 0, 0, 0.2)");
					 display.css("border-width","1px");
			}else{
					 display.css("top",'calc(100% - 1px)');
					 display.css("box-shadow","0px 5px 10px rgba(0, 0, 0, 0.2)");
					 display.css("border-width","1px");
			}
			 display.find(".mCustomScrollBox .mCSB_dragger_bar").css("width","6px");
		};
	// End of Select

	var SlideChoose = function(element, options) {
		this.options = $.extend({}, $.fn.slideChoose.defaults, options);
		this.path = [];
		this.$target = $(element);
		this.$element = $('<div class="ui-hz-widget ui-slide-choose">');
		this.$wrap = $('<div class="slidechoose-widget">');
		var $icon = $('<span>').addClass('ui-select-icon');
		this.$wrap.insertAfter(this.$target).append(this.$target).append($icon);
		this.$dropdown = $('<div class="ui-select-dropdown">');
		this.$contentbar = $('<div class="ui-slide-choose-bar">');
		this.$inputDiv = $('<div class="hide">');
		this.$inputDiv.insertAfter(this.$target);
		this.$contentbar.append($('<span>').append($(SlideChoose.TITLE_LINK).text(this.options.root).data('kv', {
			key : '',
			level : 0
		})));
		this.$element.append(this.$contentbar, this.$dropdown);
		$(this.options.append).append(this.$element);

		this.options.inputName = this.options.name || this.$target.attr('name') + 'Value';

		this.maxLevel = this.options.maxLevel;
		this.level = 0;
		this.titles = [];
		// key value
		this.currentList = {};
		this.dataAll = {};

		var values = this.$target.data('values');
		if (this.options.values && values) {
			values = values.split('|').map(function(str) {
				var arr = str.split(':');
				return {
					key : arr[0],
					value : arr[1]
				};
			});
		}

		this.options.values = this.options.values || values;
		this.options.table = this.options.table || this.$target.data('table');

		this.options.key = this.options.key || this.$target.data('key');
		if (this.options.values) {
			this._initData(this.options.values);
		} else {
			// this.options.key, this.options.fType
			var p = this.$target.data('parentid') ||'';
			this.path.push(p);
			var value = this.$target.data('value')||'';
			if(value){
				this.loadname(value)
			}
			this.loadData(p);
		}
		this.addEvents();
	};
	SlideChoose.TITLE_LINK = '<a href="javascript:void(0);" class="ui-slide-title-last">';
	SlideChoose.prototype = {
		constructor : SlideChoose,
		reset : function() {
			this.clear();
			if (this.options.values) {
				this._initData(this.options.values);
			} else {
				// this.options.fType
				this.loadData('');
			}
		},
		values : function(val) {
			this.clear();
			this._initData(val);
		},
		clear : function() {
			this.level = 0;
			this.titles = [];
			this.currentList = {};
			this.$dropdown.empty();
			this.$inputDiv.empty();
			this.$target.val('');
			this.$contentbar.find('span:gt(0)').remove().end().find('span a').addClass('ui-slide-title-last');
		},
		_initData : function(values) {
			this.level = values.length - 1;
			for ( var i = 0; i < values.length; i++) {
				var item = values[i];
				if (values.length - 1 > i) {
					this.addTitle(item, i + 1);
				} else {
					this.titles[this.level] = item;
					this.showContent(item);
				}
				if (values.length - 2 == i) {
					this.loadData(item.key);
				}
			}
		},
		empty:function(){
			this.$inputDiv.empty();
			this.$target.val('');
			this.$element.find('.ui-slide-choose-bar').find('span').eq(0).children("a").trigger('click')
			this.loadData('');
		},
		callshow:function(){
			var p = this.path;
			var value = this.$target.attr('value');
			if(p.length==0){
				this.path = value.split(';');
			}
		},
		setTitle:function(value){
			var v;
			if(value){
				v = value;
			}else{
				v = this.$target.val();
			} 
			this.$target.attr('title',v);
		},
		loadname :function(val){
			var _this = this;
			Utils.getSlideNameList({
				url : this.options.url,
				type : this.options.key,
				values:	val,
				table : this.options.table,
				success : function(data) {
					var d = data.returnObject;
					if(d==null){
						return;
					}
					var re='';
					for(var i=0;i<d.length;i++){
						d[i] = d[i]?d[i]:{'sortNo':'','sortName':''}
						var t = {
								  key:d[i].sortNo,
								  value:d[i].sortName
								  }
						if(i==0){
							re = re+d[i].sortName;
						}else{
							if(re){
								re = re +' > '+ d[i].sortName;
							}else{
								re =d[i].sortName;
							}
						}
					}
					_this.$target.val(re);
					_this.setTitle();
				}
			});
		},
		showvalues:function(v){
			this.level = v.length - 1;
			for ( var i = 0; i < v.length; i++) {
				var item = v[i];
				if (v.length - 1 > i) {
					this.addTitle(item, i + 1);
				} else {
					this.titles[this.level] = item;
					this.showContent(item);
				}
			}
		},
		loadData : function(fType) {
			var that = this;
			var value = this.$target.data("value")||'';
			var values = [];
			while(value.indexOf(";")>0){
				var i = value.indexOf(";");
				values.push(value.substring(0,i));
				value = value.substring(i+1,value.length)
			}
			var cur = this.dataAll[fType];
			if (cur) {
				this.generateList(cur);
			} else {
				var _this = this;
				Utils.getSlideList({
					url : this.options.url,
					type : this.options.key,
					ftype : fType,
					values:	values,
					path : that.path,
					table : this.options.table,
					success : function(data) {
						_this.generateList(data.returnObject);
						_this.addData(fType, data.returnObject);
						_this.addHideinput();
					}
				});
			}
		},
		addHideinput:function(){
			var $el = this.$target;
			var value = $el.data('value');
			var name = $el.attr('name')+'Value';
			if(value){
				var arr = value.split(';');
				$el.next('div.hide').empty();
				$.each(arr,function(i,v){
					var input = $('<input type="hidden" name="" />');
					$el.next('div.hide').append(input);
					input.attr('name',name);
					input.attr('value',v);
				})
			}
		},
		addTitle : function(kv, level) {
			this.$contentbar.find('.ui-slide-title-last').removeClass('ui-slide-title-last');
			var $span = $('<span>');
			var $a = $(SlideChoose.TITLE_LINK);
			$span.text(this.options.split).append($a.text(kv.value).data('kv', $.extend({
				level : level
			}, kv)));
			this.$contentbar.append($span);
			this.titles.push(kv);
			if(this.options.actual){this.showContent();}
		},
		addData : function(key, data) {
			// var list = {};
			// for ( var i = 0; i < data.length; i++) {
			// var item = data[i];
			// list[item.sortNo] = item;
			// }
			this.currentList = data;
			this.dataAll[key] = data;
			// this.currentList.next = list;
			// this.currentList = this.currentList.next;
		},
		choosePre : function(kv,index) {
			if (this.moving) {
				return;
			}
			var length = this.path.length;
			this.path = this.path.splice(0,index+1);
			//console.log(this.path)
			this.moving = true;
			if (kv.level == 0) {
				this.$inputDiv.empty();
				this.$target.val('');
			}
			var _this = this;
			this.$dropdown.css({
				height : this.$dropdown.height()
			});
			this.$ul.animate({
				left : this.$dropdown.width()
			}, 300, function() {
				$(this).remove();
				_this.moving = false;
				_this.$dropdown.css({
					height : 'auto'
				});
				_this.$dropdown.scrollTop(0);
			});
			var cur = this.dataAll[kv.key];
			if (!cur) {
				this.loadData(kv.key);
			} else {
				this.generateList(cur);
			}
			this.titles = this.titles.slice(0, kv.level);
			this.level = kv.level;
			this.end = false;
		},
		chooseNext : function(kv) {
			if (this.moving) {
				return;
			}
			this.path.push(kv.key);
			//console.log(this.path)
			if (!kv.childrenExist || this.maxLevel == this.level) {
				this.titles[this.level] = kv;
				if(this.options.controlBit){
					if(!this.end){
						this.$contentbar.find('.ui-slide-title-last').removeClass('ui-slide-title-last');
						var $span = $('<span>');
						var $a = $(SlideChoose.TITLE_LINK);
						$span.text(this.options.split).append($a.text(kv.value));
						this.$contentbar.append($span);
					}else{
						this.$contentbar.find('.ui-slide-title-last').text(kv.value);
					}
				}
				this.$target.val("");
				this.showContent(kv);
				this.close();
				this.end = true;
			} else {
				this.moving = true;
				this.level++;
				this.addTitle(kv, this.level);
				var _this = this;
				this.$dropdown.css({
					height : this.$dropdown.height()
				});
				this.$ul.animate({
					left : -this.$dropdown.width()
				}, 300, function() {
					$(this).remove();
					_this.moving = false;
					_this.$dropdown.css({
						height : 'auto'
					});
					_this.$dropdown.scrollTop(0);
				});
				var cur = this.dataAll[kv.key];
				if (!cur) {
					this.addvalue();
					this.loadData(kv.key);
				} else {
					this.generateList(cur);
				}
			}
		},
		addvalue:function(){
			var $el = this.$target;
			var temp = this.path.slice(1);
			$el.data('value',temp.join(";"));
		},
		showContent : function() {
			var content = '';
			this.$inputDiv.empty();
			this.options.inputName = this.options.name || this.$target.attr('name') + 'Value';
			for ( var i = 0; i < this.titles.length; i++) {
				var item = this.titles[i];
				content += item.value;
				if (i != this.titles.length - 1) {
					content += this.options.split;
				}
				this.$inputDiv.append($('<input type="hidden">').attr('name', this.options.inputName).val(item.key));
			}
			this.$target.val(content);
		},
		generateList : function(data) {
			if(data&&data.length>0){
				this.$ul = $('<ul>');
				for ( var i = 0; i < data.length; i++) {
					var item = data[i];
					var $li = $('<li>').text(item.sortName).data('kv', {
						key : item.sortNo,
						value : item.sortName,
						childrenExist : item.childrenExist
					});
					// TODO
					if (item.childrenExist) {
						$li.append('<span class="ui-slide-choose-next">');
					}
					this.$ul.append($li);
				}
				this.$dropdown.empty().append(this.$ul);
				this.addmcuScrollbar();
			}

		},
		addEvents : function() {
			var _this = this;
			this.$wrap.find("span.ui-select-icon").bind(this.options.events.open,function(){
					_this.$target.trigger(_this.options.events.open);
			})
			this.$target.bind(this.options.events.open, $.proxy(this.open, this));
			this.$dropdown.on('click.ui-slide-choose', 'li', function() {
				var $this = $(this);
				_this.chooseNext($this.data('kv'));
			});
			this.$contentbar.on('click', 'a:not(".ui-slide-title-last")', function() {
				var $this = $(this);
				var index = $(this).parent().index();
				if(index==0&&_this.$target.data('parentid')){
					var parentid = _this.$target.data('parentid')
					var k = $this.data('kv');
					k.key = parentid;
				}
				_this.choosePre($this.data('kv'),index);
				$this.addClass('ui-slide-title-last').parent().find('~ span').remove();
				if(_this.options.controlBit){
					_this.end = false;
					_this.$target.val('');
				}
			});
			$(window).bind('resize.ui-slide-choose', $.proxy(this.resize, this));
		},
		open : function(event) {
			if (this.$target.is('[slide-readonly]')) {
				return;
			}
			if (this.$target.is('[readonly]')) {
				return;
			}
			this.resize();
			this.$element.addClass('ui-slide-choose-open');
			this.addmcuScrollbar();
			$(document).bind('mousedown.ui-slide-choose', $.proxy(this.close, this));
		},
		addmcuScrollbar:function(){
//			if($.isFunction(this.$dropdown.mCustomScrollbar)){
//				this.$dropdown.mCustomScrollbar("destroy");
//				this.$dropdown.mCustomScrollbar({
//						theme:"dark",
//						 advanced:{
//							  updateOnContentResize:true
//						  }
//					})
//			}
		},
		resize : function() {
			var offset = this.$target.offset();
			var height = this.$target.outerHeight();
			var width = this.$target.outerWidth();
			this.$element.css({
				left : offset.left,
				top : offset.top + height,
				width : width
			});
		},
		close : function(event) {
			if (event && (this.$element.find(event.target).size() != 0 || this.$target.is(event.target))) {
				return;
			}
			$(document).unbind('mousedown.ui-slide-choose');
			$(window).unbind('resize.ui-slide-choose');
			this.$element.removeClass('ui-slide-choose-open');
			if(event){
				var link_a = this.$contentbar.find("a"),
					value = '';
				if(this.$target.val()!=''){
					if(link_a.length>1){
						for(var i = 1;i < link_a.length;i++){
							value = (value==''? value:value+' > ') + $(link_a[i]).html();
						}
					}
				}else{
					this.$contentbar.find("a:first").trigger('click');
				}
				if(value==''&&this.$inputDiv.children().length>0){
					
				}else{
					if(this.options.controlBit){
						if(!this.end){
							this.$target.val('');
						}else{
							this.$target.val(value);
						}
					}else{
						this.$target.val(value);
					}
				}
			}
			if(this.$target.val()==''){
				this.$inputDiv.empty();
			}else{
				var v = this.$target.val().match(/>/g) == null ? 1:this.$target.val().match(/>/g).length+1;
				if(v < this.$inputDiv.children().length){
					this.$inputDiv.children(':last').remove();
				}
			}
			this.setTitle();
		}
	};

	$.fn.slideChoose = function(option, value) {
		var methodReturn = null;
		var $set = this.each(function() {
			var $this = $(this);
			var data = $this.data('slideChoose');
			var options = typeof option === 'object' && option;
			if (!data) {
				$this.data('slideChoose', (data = new SlideChoose(this, options)));
			}
			if (typeof option === 'string') {
				methodReturn = data[option](value);
			}
		});
		return (methodReturn === null) ? $set : methodReturn;
	};
	$.fn.slideChoose.defaults = {
		events : {
			open : 'click'
		},
		root : '请选择',
		split : ' > ',
		append : 'body',
		controlBit : false,
		fType : '',
		actual: false
	};
	$.fn.slidereback = function(value){
		var el = $(this).length>1 ? $(this).eq(0):$(this);
		var name = el.attr('name')+'Value';
		if(value){
			el.attr("data-value",value);
			el.slideChoose("loadname",value);
			var arr = value.split(';');
			el.next('div.hide').empty();
			$.each(arr,function(i,v){
				var input = $('<input type="hidden" name="" />');
				el.next('div.hide').append(input);
				input.attr('name',name);
				input.attr('value',v);
			})
		}
	};

	$.fn.slideChoose.Constructor = SlideChoose;
	// End of Slide Choose
	// End of Slide Choose

	// Strat of Validate, depend on jQueryUI
	var Validate = function(element, options) {
		this.options = $.extend({}, $.fn.validate.defaults, options);
		this.$element = $(element);
		this.$element.addClass('utils-validation');

		this.init();
	};
	Validate.prototype = {
		init : function() {
			if (this.options.rules) {
				this.rules = this.options.rules;
			} else if (this.options.rule) {
				this.rules = [ this.options.rule ];
			}
			this.addEvents();
		},
		addEvents : function() {
			this.$element.bind(this.options.events.active + '.validation', $.proxy(this.action, this));
		},
		action : function() {
			var tooltip = this.options.tooltip;
			tooltip = $.extend({}, {
				items : this.$element
			}, tooltip);
			for ( var i = 0; i < this.rules.length; i++) {
				var RULE = this.rules[i];
				if (!RULE.rule(this.$element.val())) {
					tooltip.content = RULE.fail || RULE.rule.fail;
					this.createTip(tooltip);
					return;
				}
			}
			this.destroyTip(tooltip);
		},
		createTip : function(tooltip) {
			this.$tip = this.$element.tooltip(tooltip).tooltip('open');
			this.$element.addClass('error');
		},
		destroyTip : function() {
			if (this.$tip) {
				this.$tip.tooltip('destroy');
				delete this.$tip;
				this.$element.removeClass('error');
			}
		}
	};
	$.fn.validate = function(option, value) {
		var methodReturn = null;
		var $set = this.each(function() {
			var $this = $(this);
			var data = $this.data('validate');
			var options = typeof option === 'object' && option;
			if (!data) {
				$this.data('validate', (data = new Validate(this, options)));
			}
			if (typeof option === 'string') {
				methodReturn = data[option](value);
			}
		});
		return (methodReturn === null) ? $set : methodReturn;
	};
	$.fn.validate.defaults = {
		events : {
			// hide : 'mouseout',
			// show : 'mouseover',
			active : 'blur'
		},
		tooltip : {
			// items : this,
			content : 'Error',
			// show : true,
			// track : true,
			tooltipClass : "input-tooltip-error",
			position : {
				my : 'left+10px',
				at : 'right'
			}
		}
	};
	$.fn.validate.Constructor = Validate;
	// End of Validate

	//tab start
	$.fn.tabChange=function(num,direction){//num:默认显示,direction:方向
		var $tabArea=$(this);//获取作用域
		if(direction=="h"){//根据参数加水平或竖排样式
			$tabArea.addClass("tab-h");
		}else if(direction=="v"){
			$tabArea.addClass("tab-v");
		}else{
			$tabArea.addClass("tab-h");
		}
		var $tabObj=$tabArea.find(".tab-title a");//获取作用域下的点击对象
		$tabObj.eq(num-1).addClass("active");//根据参数设置默认显示项
		var $tabCon=$tabArea.find(".tab-main>.tab-con");
		$tabCon.eq(num-1).show().siblings().hide();
		$tabObj.click(function(){
			$tabObj.removeClass("active");
			$(this).addClass("active");
			var index=$tabObj.index(this);//找到对应的索引值
			$tabCon.eq(index).show().siblings().hide();
		});
	};
	//tab end

	//drop start
	$.fn.dropMod=function(num,callBack){//num:默认展开
		var $dropArea=$(this);
		var $dropModTitle=$dropArea.find(".drop-mod-title");//所有模块标题栏
		var $dropModCon=$dropArea.find(".drop-mod-con");//模块内容
		var $dropTool=$dropArea.find(".drop-tool");//模块伸缩图标区
		$dropTool.addClass("drop-tool-on").text("+");//默认全部闭合
		$dropModCon.hide();
		var $defDropModTitle=$dropModTitle.eq(num-1);//根据参数设置默认展开项
		$defDropModTitle.find(".drop-tool").removeClass("drop-tool-on").addClass("drop-tool-off").text("-").end().next(".drop-mod-con").show();
		$dropModTitle.each(function(){
		$(this).find('.drop-tool').bind("click",function(){
			var myParent = $(this).closest('.drop-mod-title');
			var $nextDropModCon=$(myParent).next(".drop-mod-con");//点击对象对应的模块
			var $childDropTool=$(myParent).find(".drop-tool");//点击对象对应的伸缩图标区
			if($nextDropModCon.is(":hidden")){//判断对应对象是否显示
				$dropTool.addClass("drop-tool-on").text("+");
				$childDropTool.removeClass("drop-tool-on").addClass("drop-tool-off").text("-");
				$dropModCon.slideUp();
				if(callBack != null){
					$nextDropModCon.slideDown('1000',callBack);
				}else{
					$nextDropModCon.slideDown('1000');
				}
				
			}else if($nextDropModCon.is(":visible")){
				$dropTool.addClass("drop-tool-on").text("+");
				if(callBack != null){
					$dropModCon.slideUp('1000',callBack);
				}else{
					$dropModCon.slideUp('1000');
				}
			}
		});
		});
	};
	//drop end

	//dialog start
	//success
	var config = {
			$element:$('body'),
			type : 'dialog',			 // 'tip','dialog'
			content : '',			 //要放到tip中的内容
			width : 310,			 // 容器宽度
			height : 160,			 // 容器高度
			animate:'normal',		 //出现方式
			closeButton:true,		 //是否有关闭按钮，默认没有
			buttons :{
				"确定" : function(t,that){
					that.close();
					if($.isFunction(fn1)){
						fn1();
					}
				}
			},
			needmask:true,
			buttonClass:['tip-dilog-show','tip-dilog-show'],
			needmin : false,
			needscroll:true,
			endcallback :'',
			needscroll:true,
			endcallback:function(a,b,c){
				var a = c.cache.$tipContent.height(98);
				//c.cache.$tipContent.mCustomScrollbar('update');
			}
	}
	HZBank.showSuccess=function (textCon,fn){
		var $showModSuc=$('<span class="tip-dialog-suc"><i class="icons icon-correct"></i>'+textCon+'</span>');
		var self = config;
			self.content = $showModSuc;
			self.buttons = {
					"确定" : function(t,that){
						that.close();
						if($.isFunction(fn)){
							fn();
						}
					}
				};
		    self.callback =function(that){
		    	that.close();
		    	if($.isFunction(fn)){
		    		fn();
		    	}
			}
		    $("body").showtip('init',self);
		    $("body").showtip('recontent',$showModSuc);
//		$showModSuc.dialog({
//			title : "提示",
//			minWidth : 390,
//			minHeight : 200,
//			modal : true,
//			dialogClass:"hzbank-dialog",
//			buttons :{
//				"确定" : function(){
//					if($.isFunction(fn)){
//						fn();
//					}
//					$(this).dialog("close");
//				}
//			}
//		});
	},
	//fail
	HZBank.showFail=function (textCon,fn){
		var $showModFail=$('<span class="tip-dialog-fail"><i class="icons icon-mistake"></i>'+textCon+'</span>');
		var self = config;
		self.content = $showModFail;
		self.buttons = {
				"确定" : function(t,that){
					that.close();
					if($.isFunction(fn)){
						fn();
					}
				}
			};
		self.callback =function(that){
			that.close();
	    	if($.isFunction(fn)){
	    		fn();
	    	}
		}
	    $("body").showtip('init',self);
	    $("body").showtip('recontent',$showModFail);
	},
	//warn
	HZBank.showWarn=function (textCon,fn){
		var $showModWarn=$('<span class="tip-dialog-warn"><i class="icons icon-prompt"></i>'+textCon+'</span>');
		var self = config;
		self.content = $showModWarn;
		self.buttons = {
				"确定" : function(t,that){
					that.close();
					if($.isFunction(fn)){
						fn();
					}
				}
			};
		self.callback =function(that){
			that.close();
	    	if($.isFunction(fn)){
	    		fn();
	    	}
		}		
	    $("body").showtip('init',self);
	    $("body").showtip('recontent',$showModWarn);
	},
	//confim
	HZBank.showConfim=function (textCon,fn1,fn2){
		var $showConfim=$('<span class="tip-dialog-confim">'+textCon+'</span>');
		var self = config;
		self.content = $showConfim;
//		self.height = 145;
		self.buttons ={
				"是" : function(t,that){
					that.close();
					if($.isFunction(fn1)){
						fn1();
					}
				},
				"否" : function(t,that){
					that.close();
					if($.isFunction(fn2)){
						fn2();
					}
				}
			}
		self.endcallback = function(a, b, c){
			var a = c.cache.$tipContent.height(98);
			//c.cache.$tipContent.mCustomScrollbar('update');
			c.getButton().eq(1).addClass('tip-button-gray');
		};
		self.callback = $.noop;
		 $("body").showtip('init',self);
	    $("body").showtip('recontent',$showConfim);
	},
	//dialog end
	/**************单文件上传********
	 * {
	 * actionUrl:后台地址
	 * config：配置文件  {
	 * 						uploadcallback:上传结束后的回调，
	 * 						imgcallback:文件选择后的回调  返回参数为 img的src地址
	 * 						storeBu    :  保存按钮，
	 * 						ViewCon   ：预览节点
	 * 					}
	 * }
	 * by--zhanghuan
	 * *********************/
	 HZBank.SingleUpload = function(actionUrl,config){
		$uploader = $('<div id="single-uploader" class="hide" uploaded=true></div>');
		if($("#single-uploader").length==0){
			$uploader.appendTo('body');
		}
//		//判断上次上传文件是否结束
//		if($("#single-uploader").attr('uploaded')==false){
//			return;
//		}
		var con = {
				uploadcallback:$.noop,
				imgcallback:$.noop,
				storeBu:'',
				ViewCon:''
		};
		arguments.length==2 && $.extend(con,arguments[1]);
		var Bu = con.storeBu;
		var view = con.ViewCon;
		if(!con.storeBu){
			return;
		}
		var uploader = new qq.FileUploader({
        	uploadButtonText: '<i class="icon-select icon-white"></i> 选择文件',
        	cancelButtonText: '取消上传',
        	failUploadText: '上传失败',
			dragZoneText: '拖放',
			encoding: 'multipart', // 新增
        	autoUpload: false,
        	onComplete: function(fileType,fileName,result){
//        		$("#single-uploader").attr('uploaded',true);			//上传完成后的回调，并把状态设为true，为上传结束
        		HZBank.Utils.formmask('remove',Bu);
//        		HZBank.Core.showMsg();
        		if($.isFunction(con.uploadcallback)){
        			con.uploadcallback(fileType,fileName,result);
        		}
        	},
        	onError : function(id, fileName, xhr){
        		HZBank.showFail(fileName+xhr);
        	},
        	disableCancelForFormUploads: true,
            element: document.getElementById('single-uploader'),
            action: actionUrl,
            acceptFiles: null,
            multiple: false,
			template: '<div class="qq-uploader">' +							//style="visibility:hidden;"
				'<div class="qq-upload-drop-area"><span>{dragText}</span></div>' +
				'<div class="qq-upload-buttongroup"><div class="qq-upload-button btn btn-primary">{uploadButtonText}</div> ' +
				'<div id="triggerUpload" class="qq-upload-button btn"><i class="icon-upload icon-white"></i> 上传文件</div> ' +
				'<div id="triggerClean" class="qq-upload-button btn"><i class="icon-ban-circle icon-white"></i> 清除文件</div></div>' +
				'<ul class="qq-upload-list"></ul>' +
				'</div>'
        });
		//绑定事件，文件选择后返回文件的链接地址
		$("#single-uploader").find('input[type=file]').unbind('change.zh').bind('change.zh',function(e){
			var reader = new FileReader();
	        reader.onload = function( evt ){
	        	if($.isFunction(con.imgcallback)){
        			con.imgcallback(evt.target.result);
        		}
	        	if(view){
	        		var a = $("<img src='"+evt.target.result+"'/>")
					view.html(a);
	        	}
	        }
	       reader.readAsDataURL(this.files[0]);
		});
		Bu.unbind('click.zh').bind('click.zh',function(){
			//状态设为上传中
			$("#single-uploader").attr('uploaded',false);
			//开始上传
		    uploader.uploadStoredFiles();
		    HZBank.Utils.formmask('mask',Bu,'till');
		})
		$("#single-uploader").find(".qq-upload-button input").trigger("click");
	},
	//fileuploader start
	HZBank.showUpload = function(actionUrl,config){
		var con = config;
		var tip_con = {
				$element : con.el||'',
				type  :con.type || 'dialog',  				 //弹出类型， 'tip','dialog'
				title : con.title||'文件上传',			//标题内容
				content:'',		//内容
				height:con.height || 400,
				width:con.width || 550,
				position : con.position||'bottom',
				animate:con.animate || 'slide',			////出现方式  fade  normal
				animatetime:300,			//动画出现的时间
				needbind:true,
				needscroll:true,
				closeButton:true,			//是否有关闭按钮，默认没有
				buttons:{					// footer 按钮回调函数 
					'开始上传':function(){
						$("#triggerUpload").trigger("click");
					},
					'选择文件':function(a,b){
						$(".qq-upload-button input").trigger("click");
						//b.cache.$tipContent.mCustomScrollbar("update")
					}
				},
				callback:con.callback || function(that){that.hide()}
			}
		    con.el.showtip();
			$uploader = $('<div id="bootstrapped-uploader" ></div>');
			if($("#bootstrapped-uploader").length==0){
				$uploader.appendTo('body');
			}
			var uploader = new qq.FileUploader({
	        	uploadButtonText: '<i class="icon-select icon-white"></i> 选择文件',
	        	cancelButtonText: '取消上传',
	        	failUploadText: '上传失败',
				dragZoneText: '拖放',
				encoding: 'multipart', // 新增
				params: config.params,
	        	autoUpload: false,
	        	onComplete: config.uploadcallback ||$.noop,
	        	onError : function(id, fileName, xhr){
	        		HZBank.showFail(fileName+xhr);
	        	},
	        	disableCancelForFormUploads: true,
	            element: document.getElementById('bootstrapped-uploader'),
	            action: actionUrl,
	            acceptFiles: config.acceptFiles ||null,
	            multiple: config.multiple || false,
				template: '<div class="qq-uploader">' +							//style="visibility:hidden;"
					'<div class="qq-upload-drop-area"><span>{dragText}</span></div>' +
					'<div class="qq-upload-buttongroup"><div class="qq-upload-button btn btn-primary">{uploadButtonText}</div> ' +
					'<div id="triggerUpload" class="qq-upload-button btn"><i class="icon-upload icon-white"></i> 上传文件</div> ' +
					'<div id="triggerClean" class="qq-upload-button btn"><i class="icon-ban-circle icon-white"></i> 清除文件</div></div>' +
					'<ul class="qq-upload-list"></ul>' +
					'</div>'
	        });
		    $('#triggerUpload').unbind().click(function() {
				uploader.uploadStoredFiles();
			});
			$('#triggerClean').unbind().click(function() {
				uploader.clearStoredFiles();
		    });
			
			if(config){
				var c = tip_con;
				c.content = $('#bootstrapped-uploader');
				 con.el.showtip('init',c)
				$(".qq-upload-buttongroup").css('display','none');
			}else{
				$("#bootstrapped-uploader").dialog({
					title:"文件上传",
					dialogClass:"hzbank-dialog",
					width:550,
					height:400
				});
			}
	},
	//fileuploader end
	//overlay start
	HZBank.overLay = function(options){
		var opt = {
				title : "标题",
				width : 600,
				height : 500,
				close : "destroy",//destroy为移除,hidden为隐藏
				modal : true
//				title     : "文件标题",          //弹出窗口的标题名称
//				type      : "加载类型",          //分iframe和id，iframe为加载页面，id为加载当前页面的一个模块
//				url       : "加载路径",			//type为iframe时用，为加载页面的路径
//				id        : "为iframe加入一个",    //type为iframe时用，为iframe指定一个id
//				showModId : "要显示模块id名称",//type为id时用，为要显示模块的id
//				close     : "关闭方式",         //分destroy和hidden，destroy为移除，hidden为隐藏
//				width     : 600,             //设置弹框宽度
//				height    : 500              //设置弹框高度
		};
		$.extend(opt,options);
		var me = this;
		var _overlay;
		me.init = function(){
			var overLayId = opt.id;
			var showModId = opt.showModId;
			if($(".hzbank-dialog #"+overLayId).length>0 || $(".hzbank-dialog #"+showModId).length>0){
				me.open();
			}else if(opt.type=="iframe"){
				$showOverLay=$("<iframe class='win-iframe' id='"+overLayId+"' src='"+opt.url+"'></iframe>");
				_overlay = $showOverLay.dialog({
					title : opt.title,
					width : opt.width,
					height : opt.height,
					dialogClass : "hzbank-dialog",
					modal:opt.modal
				});
			}else if(opt.type=="id"){
				_overlay = $("#"+showModId).dialog({
					title : opt.title,
					width : opt.width,
					height : opt.height,
					dialogClass : "hzbank-dialog",
					modal:opt.modal
				});
			}
			$("#"+overLayId).prev(".ui-dialog-titlebar").find(".ui-dialog-titlebar-close").bind("click",function(){
				me.close();
			});
			$("#"+showModId).prev(".ui-dialog-titlebar").find(".ui-dialog-titlebar-close").bind("click",function(){
				me.close();
			});
		};
		me.close = function(){
			if(opt.close=="destroy"){
				_overlay.dialog('destroy');
			}else if(opt.close=="hidden"){
				_overlay.dialog( 'close' );

			}
		};
		me.open = function(){
			_overlay.dialog( 'open' );
		};
		me.reflash = function(){
			me.init();
		};
	};
	//overlay end

	this.HZBank = HZBank;
})(this);